package com.easychat.websocket.netty;

import com.easychat.config.AppConfig;
import com.easychat.utils.StringTools;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author: yudaxian
 * @Description: TODO
 * @DateTime: 2024/8/18 10:31
 **/
@Component
public class NettyWebSocketStarter implements Runnable {

    private static final Logger log = LoggerFactory.getLogger(NettyWebSocketStarter.class);
    private static EventLoopGroup bossGroup = new NioEventLoopGroup(1);

    private static EventLoopGroup workerGroup = new NioEventLoopGroup();

    @Resource
    private HandlerWebSocket handlerWebSocket;

    @Resource
    private AppConfig appConfig;

    @PreDestroy
    public void close() {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

    @Override
    public void run() {
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup);
            serverBootstrap.channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .childHandler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            // 对http协议进行编解码
                            pipeline.addLast(new HttpServerCodec());
                            // 对http消息进行聚合
                            pipeline.addLast(new HttpObjectAggregator(64 * 1024));
                            // 心跳：设置心跳规则
                            pipeline.addLast(new IdleStateHandler(60, 0, 0, TimeUnit.SECONDS));
                            // 超时处理器：处理心跳
                            pipeline.addLast(new HandlerHeartBeat());
                            // 将http协议升级为ws协议,对websocket支持
                            pipeline.addLast(new WebSocketServerProtocolHandler("/ws", null, true, 64 * 1024, true, true, 10000L));
                            // 定义自定义handler处理
                            pipeline.addLast(handlerWebSocket);
                        }
                    });
            Integer port = appConfig.getWsPort();
            String property = System.getProperty("ws.port");
            if (!StringTools.isEmpty(property)) {
                port = Integer.valueOf(property);
            }
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            log.error("启动netty 成功，端口号：{}", appConfig.getWsPort());
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("启动netty 失败", e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
